//
//  ShareMenager.m
//  WorldOfFacts_V2
//
//  Created by Demjanko Denis on 14.12.12.
//  Copyright (c) 2012 it-dimension. All rights reserved.
//

#import "ShareMenager.h"
#import "UIImageView+WebCache.h"

@implementation ShareMenager

@synthesize completionHandler;

+ (ShareMenager*)sharedManeger{
    __strong static ShareMenager* _sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[ShareMenager alloc]init];
    });
    return _sharedManager;
}

-(id)init{
    self = [super init];
    
    vkontakte = [Vkontakte sharedInstance];
    vkontakte.delegate = self;
    
    facebook = [[Facebook alloc] initWithAppId:@"235245486548884" andDelegate:self];        
    if ([[NSUserDefaults standardUserDefaults]  objectForKey:@"FBAccessTokenKey"] && [[NSUserDefaults standardUserDefaults]  objectForKey:@"FBExpirationDateKey"]) {
        facebook.accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"FBAccessTokenKey"];
        facebook.expirationDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"FBExpirationDateKey"];
    }
    
    return self;
}

-(void)postVKFact:(NSMutableDictionary*)_fact fromViewController:(UIViewController*)_parentVC withCompletionHandler:(SHResult)handler{
    fact = [NSMutableDictionary dictionaryWithDictionary:_fact];
   
    parentVC = _parentVC;

    self.completionHandler = handler;
    
    if (![vkontakte isAuthorized]) {
        [vkontakte authenticate];
        
        [[[[UIApplication sharedApplication]keyWindow] viewWithTag:20] removeFromSuperview];

    }
    else{
        NSString* url = [NSString stringWithFormat:
                         @"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&pageNumber=0&sortOrdering=1&type=Purple+Software&mt=8", @"488108471"];
        
        NSMutableArray *imgs = [fact objectForKey:@"images"];

        UIImageView *avatar_view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 1, 32, 32)];
        
        [avatar_view setImageWithURL:[NSURL URLWithString:[imgs objectAtIndex:0]] placeholderImage:nil options:0 success:^(UIImage *image, BOOL cached) {
            [vkontakte postImageToWall:image text:[fact valueForKey:@"full_description"] link:[NSURL URLWithString:url]];
        } failure:^(NSError *error) {
            self.completionHandler(FALSE);
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:@"Изображение не загружено" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }];
        
    }
}



#pragma mark - VkontakteDelegate

- (void)vkontakteDidFailedWithError:(NSError *)error{
    self.completionHandler(FALSE);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

- (void)showVkontakteAuthController:(UIViewController *)controller{
    [parentVC presentModalViewController:controller animated:YES];
}

- (void)vkontakteAuthControllerDidCancelled{
    [parentVC dismissModalViewControllerAnimated:YES];
   
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ON_PHOTOBROWSER_DONE" object:nil];

    self.completionHandler(FALSE);
}

- (void)vkontakteDidFinishLogin:(Vkontakte *)_vkontakte{
    [parentVC dismissModalViewControllerAnimated:YES];
   
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ON_PHOTOBROWSER_DONE" object:nil];

    NSString* url = [NSString stringWithFormat:
                     @"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&pageNumber=0&sortOrdering=1&type=Purple+Software&mt=8", @"488108471"];
    
    NSMutableArray *imgs = [fact objectForKey:@"images"];
    
    UIImageView *avatar_view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 1, 32, 32)];
    
    [avatar_view setImageWithURL:[NSURL URLWithString:[imgs objectAtIndex:0]] placeholderImage:nil options:0 success:^(UIImage *image, BOOL cached) {
        [vkontakte postImageToWall:image text:[fact valueForKey:@"full_description"] link:[NSURL URLWithString:url]];
    } failure:^(NSError *error) {
        self.completionHandler(FALSE);
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:@"Изображение не загружено" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }];
}

- (void)vkontakteDidFinishPostingToWall:(NSDictionary *)responce{
    self.completionHandler(TRUE);
}

#pragma mark Facebook

-(void)postFBFact:(NSMutableDictionary*)_fact fromViewController:(UIViewController*)_parentVC withCompletionHandler:(SHResult)handler{
    fact = [NSMutableDictionary dictionaryWithDictionary:_fact];
    
    parentVC = _parentVC;
    
    self.completionHandler = handler;
    
    [self loginToFacebook];
}

-(void)loginToFacebook{    
    if (![facebook isSessionValid]) 
        [facebook authorize:[NSArray arrayWithObjects:@"publish_stream",@"publish_actions",@"offline_access",nil]];
    else{
        NSMutableArray *imgs = [fact objectForKey:@"images"];
        
        UIImageView *avatar_view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 1, 32, 32)];
        
        [avatar_view setImageWithURL:[NSURL URLWithString:[imgs objectAtIndex:0]] placeholderImage:nil options:0 success:^(UIImage *image, BOOL cached) {
            NSString* url = [NSString stringWithFormat:
                             @"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&pageNumber=0&sortOrdering=1&type=Purple+Software&mt=8", @"488108471"];
            
            NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                           url, @"link",
                                           @"Мир фактов", @"name",
                                           @"http://www.gravatar.com/avatar/8907848cb5da8ee8718dde0e0ab98dec?s=32&d=identicon&r=PG", @"picture",
                                           @"Самые лучшие и интересные факты", @"caption",
                                           @"iPhone application", @"description",
                                           [fact valueForKey:@"full_description"], @"message",
                                           nil];
            
            [facebook requestWithGraphPath:@"feed" 
                                 andParams:params 
                             andHttpMethod:@"POST" 
                               andDelegate:self];
        } failure:^(NSError *error) {
            self.completionHandler(FALSE);
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:@"Изображение не загружено" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }];
    }
}

- (void)fbDidLogin{    
    [[NSUserDefaults standardUserDefaults] setObject:facebook.accessToken forKey:@"FBAccessTokenKey"];
    [[NSUserDefaults standardUserDefaults] setObject:facebook.expirationDate forKey:@"FBExpirationDateKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self loginToFacebook];
}

- (void)fbDidLogout{

}

- (void)fbDidNotLogin:(BOOL)cancelled{
    self.completionHandler(FALSE);
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error{
    self.completionHandler(FALSE);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

- (void)request:(FBRequest *)request didLoad:(id)result{    
    self.completionHandler(TRUE);
}


@end
